﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Collections;

namespace ShenLan.Common
{
    /// <summary>
    /// 上传文件类,小洗,Email:xshai@163.com
    /// </summary>
    public class UploadFile
    {
        /// <summary>
        /// 上传文件,返回状态Hashtable["status"]和文件相对路径Hashtable["path"]
        /// </summary>
        /// <param name="hfcb">HttpFileCollectionBase,Files集合</param>
        /// <param name="inputName">input type=file的name</param>
        /// <param name="filePath">保存的路径,从网站根目录开始,如"file\\zip"</param>
        /// <returns>状态Hashtable["status"]和文件相对路径Hashtable["path"]</returns>
        public static Hashtable Upload(System.Web.HttpFileCollectionBase hfcb, string inputName, string filePath)
        {
            var ht = new Hashtable();
            try
            {
                string serverPath = System.Web.HttpContext.Current.Server.MapPath("~");

                //保存路径形式
                string toFilePath = Path.Combine(serverPath, filePath + "\\");

                //判断目录是否存在,不存在则新建
                if (!Directory.Exists(toFilePath))
                    Directory.CreateDirectory(toFilePath);

                //获取要保存的文件信息
                FileInfo file = new FileInfo(hfcb[inputName].FileName);

                //获得文件扩展名
                string fileNameExt = file.Extension;

                //生成将要保存的随机文件名
                string fileName = GetImageName() + fileNameExt;

                //获得要保存的文件路径
                string serverFileName = toFilePath + fileName;

                ////物理完整路径                    
                //string toFileFullPath = serverFileName; //HttpContext.Current.Server.MapPath(toFilePath);

                ////将要保存的完整文件名                
                //string toFile = toFileFullPath;//+ fileName;

                hfcb[inputName].SaveAs(serverFileName);

                //上传成功后网站内源图片相对路径
                string relativePath = System.Web.HttpContext.Current.Request.ApplicationPath + filePath + "/" + fileName;
                relativePath = relativePath.Replace(@"\", @"/");

                ht["status"] = "ok";
                ht["path"] = relativePath;
                return ht;
            }
            catch 
            {
                ht["status"] = "error";
                return ht;
            }
        }

        private static string GetImageName()
        {
            Random rd = new Random();
            var sb = new System.Text.StringBuilder();
            sb.Append(DateTime.Now.ToString("yyyyMMddHHmmssff"));
            sb.Append(rd.Next(0, 999999).ToString());
            return sb.ToString();
        }
    }
}